package com.xuhai.blog.admin.service.impl;

import com.google.code.kaptcha.Producer;
import com.xuhai.blog.admin.entity.CodeEntity;
import com.xuhai.blog.admin.mapper.CodeMapper;
import com.xuhai.blog.admin.service.CodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuhai.blog.common.exception.RTException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * <p>
 * 验证码表 服务实现类
 * </p>
 *
 * @author 机蜂
 * @since 2022-02-08
 */
@Service
public class CodeServiceImpl extends ServiceImpl<CodeMapper, CodeEntity> implements CodeService {

    @Autowired
    private Producer producer;

    @Override
    public BufferedImage getKaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new RTException("uuid不能为空");
        }
        /*获取验证码*/
        String code= producer.createText();
        /*初始化验证码类*/
        CodeEntity codeEntity=new CodeEntity();
        codeEntity.setUuid(uuid);
        codeEntity.setCode(code);
        /*设置验证码5分钟有效*/
        Date date=new Date();
        date.setMinutes(date.getMinutes()+5);
        codeEntity.setExpires(date);

        /*验证码信息存入数据库*/
        this.save(codeEntity);
        /*返回验证码图片*/
        return producer.createImage(code);
    }

    @Override
    public boolean checkCode(String uuid, String code) {
        CodeEntity codeEntity = this.getById(uuid);
        this.removeById(uuid);
        return codeEntity != null && codeEntity.getCode().equalsIgnoreCase(code) && codeEntity.getExpires().getTime() > System.currentTimeMillis();
    }
}
